import 'package:flutter/material.dart';
import 'package:flutter_project/config/theme_color.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../common/route_page/route_name.dart';
import 'app_bar_view.dart';

class WebPage extends StatefulWidget {
  final String? url;
  final String? title;
  final bool isRightBtn;

  const WebPage({this.url, this.title, this.isRightBtn = false, Key? key})
      : super(key: key);

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  final _key = UniqueKey();
  bool _isLoading = true;
  late WebViewController _webViewController;

  @override
  void initState() {
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) {
            if (!mounted) return;
            setState(() {
              _isLoading = false;
            });
          },
          onNavigationRequest: (request) {
            // Handle navigation.
            return NavigationDecision.navigate;
          },
          onWebResourceError: (WebResourceError error) {},
        ),
      );
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        if (!mounted) return;
        late String url;
        dynamic arguments = (ModalRoute.of(context)!.settings.arguments);
        if (widget.url?.isNotEmpty ?? false) {
          url = widget.url ?? '';
        } else if (null != arguments && arguments is Map) {
          url = arguments['url'];
        }
        if (url.startsWith('http')) {
          _webViewController.loadRequest(Uri.parse(url));
        } else {
          _webViewController.loadFlutterAsset(url);
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    dynamic arguments = (ModalRoute.of(context)!.settings.arguments);
    String? title;
    if (widget.url?.isNotEmpty ?? false) {
      title = widget.title;
    } else if (null != arguments && arguments is Map) {
      title = arguments['title'];
    }
    return Scaffold(
      backgroundColor: ThemeColor.mainBgColor,
      appBar: CommonAppWidget.navTitleBar(
        title: title ?? '',
        rightActions: [
          Visibility(
            visible: widget.isRightBtn,
            child: TextButton(
              onPressed: () {
                RouteNames.push(
                  const WebPage(
                    url: 'https://www.youtube.com/@PixVerse_Official/',
                    title: 'YouTube体验',
                  ),
                );
              },
              child: const Text('YouTube体验'),
            ),
          ),
        ],
      ),
      body: Stack(
        children: [
          Opacity(
            opacity: _isLoading ? 0 : 1,
            child: WebViewWidget(
              key: _key,
              controller: _webViewController,
            ),
          ),
          _isLoading
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : const SizedBox.shrink(),
        ],
      ),
    );
  }
}
